<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Clue as ClueModel;
use app\admin\model\Company;
use think\Db;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use app\admin\library\Auth;

/**
 * 线索管理
 *
 * @icon fa fa-user
 */
class Clue extends Backend
{
	protected $dataLimit = true;
    protected $searchFields = 'companyname,cluecontent';

    /**
     * @var \app\admin\model\Clue
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Clue');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
				->with(['admin'])
				->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
			
            return json($result);
        }
        return $this->view->fetch();
    }
	
	/**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
			$params['companyname'] = Company::where('id', $params['company_id'])->value('companyname');
			if (empty($params['companyname'])) {
				throw new Exception(__('公司名称不能为空'));
			}
			$params['admin_id'] = $this->auth->id;
			$result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
		
		if($result == false)
		{
			$this->error('保存失败');
		}

        $this->success('添加成功');
    }
	
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			$params['companyname'] = Company::where('id', $params['company_id'])->value('companyname');
			if (empty($params['companyname'])) {
				throw new Exception(__('公司名称不能为空'));
			}
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
	
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
		if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $count = $this->model->where('id', 'in', $ids)->delete();
		if ($count) {
			$this->success();
		}

        $this->error(__('No rows were deleted'));
    }
	
	/**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $row = [];
				
				$val = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();
				$row['companyname'] = is_null($val) ? '' : trim($val);
				
				$val = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();
				$row['cluecontent'] = is_null($val) ? '' : trim($val);
				
				$val = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();
				$row['telephone'] = is_null($val) ? '' : trim($val);
				
				$val = $currentSheet->getCellByColumnAndRow(5, $currentRow)->getValue();
				$row['developtime'] = is_null($val) ? 0 :(($val-25569)*86400-(8*60*60));
				
				$val = $currentSheet->getCellByColumnAndRow(6, $currentRow)->getValue();
				$row['followup'] = is_null($val) ? '' : trim($val);
				
				$val = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();
				$row['isdeal'] = (is_null($val)|| trim($val)=='否')? 0 : 1;
				
				$val = $currentSheet->getCellByColumnAndRow(8, $currentRow)->getValue();
				$row['amount'] = is_null($val) ? 0 : floatval($val);
				
				$row['admin_id'] = $this->auth->id;
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            $this->model->saveAll($insert);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
